package com.android.functionmanagement.location;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class WIFILocationMode extends LocationMode {

	public static final String TAG = "WIFILocationMode";
	private WifiManager wifiManager;
	private Scanner mScanner  = new Scanner();
	private boolean isOpenWifi = false;

	@Override
	public void init(Context context) {
		this.mContext = context;
		wifiManager = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		if (wifiManager.isWifiEnabled()) {
			isOpenWifi = true;
            mScanner.forceScan();
        }else{
        	isOpenWifi = false;
        	wifiManager.setWifiEnabled(true);
        }
	}

	@Override
	public Object getLocationInfo() {
		if (wifiManager == null) {
			new Exception("异常：必须先初始化");
		}
		if (wifiManager.isWifiEnabled()) {
			return wifiManager.getScanResults();
		}
		return null;
	}

	private class Scanner extends Handler {
		private int mRetry = 0;

		Scanner() {
		}

		void resume() {
			if (!hasMessages(0)) {
				sendEmptyMessage(0);
			}
		}

		void forceScan() {
			removeMessages(0);
			sendEmptyMessage(0);
		}

		void pause() {
			mRetry = 0;
			removeMessages(0);
		}

		@Override
		public void handleMessage(Message message) {
			if (wifiManager!= null && wifiManager.startScan()) {
				mRetry = 0;//当中有一次扫描成功mRetry=0； 
				if(mCompleteLister!=null){
					mCompleteLister.onCompleted(wifiManager.getScanResults(), SUCCESS);
					reset();
					return;
				}
			} else if (++mRetry >= 3) {//开始扫描的操作失败mRetry+1与3比较，超过三次就return  
				mRetry = 0;
				Log.d(TAG, "wifi_fail_to_scan");
				if(mCompleteLister!=null){
					mCompleteLister.onCompleted(null, ERR);
					reset();
				}
				return;
			}
			sendEmptyMessageDelayed(0, 6 * 1000);//每隔6秒，发起扫描的操作  
		}
	}

	@Override
	public void setLocationCompleteLister(LocationCompleteLister completeLister) {
		this.mCompleteLister = completeLister;
	}
	
	private void reset(){
		if(isOpenWifi){
			if(wifiManager.isWifiEnabled()){
				wifiManager.setWifiEnabled(true);
			}
		}else{
			wifiManager.setWifiEnabled(false);
		}
	}

}
